using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using BSDS.Core.Infrastructure.RemoteCommunication;

namespace BSDS.Core.Infrastructure.Logging
{
    public class Logger
    {
        private readonly string sourceName;
        private readonly TraceSource traceSource;

        private readonly List<ILogConsumer> logConsumers;

        public Logger(string sourceName, TraceSource traceSource, List<ILogConsumer> logConsumers)
        {
            this.sourceName = sourceName;
            this.traceSource = traceSource;
            this.logConsumers = logConsumers;
        }

        public void Log(string message, TraceEventType level)
        {
            const string logTemplate = "[{0}] {1}: {2}";

            var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            var logMessage = string.Format(logTemplate, time, sourceName, message);
            traceSource.TraceEvent(level, 0, logMessage);

            FowardToAllConsumers(logMessage);
        }

        public void Log(string message)
        {
            Log(message, TraceEventType.Information);
        }

        public void Log(string message, RequestResult requestResult)
        {
            const string msgTemplate = "{0}:\n Http status code: {1}\n Response contents: {2}";

            var statusCodeName = Enum.GetName(typeof (HttpStatusCode), requestResult.Status);
            var fullMessage = string.Format(msgTemplate, message, statusCodeName, requestResult.Content);

            Log(fullMessage);
        }

        private void FowardToAllConsumers(string logMessage)
        {
            foreach (var logConsumer in logConsumers)
            {
                logConsumer.Consume(logMessage);
            }
        }
    }
}